package Map排序;

import java.time.LocalDate;
import java.util.*;

public class MapSortingExample {

    // 自定义员工类
    static class Employee {
        String name;
        double salary;
        LocalDate joinDate;

        public Employee(String name, double salary, LocalDate joinDate) {
            this.name = name;
            this.salary = salary;
            this.joinDate = joinDate;
        }

        @Override
        public String toString() {
            return String.format("%-8s | 薪资: %-6.1f | 入职: %s", 
                name, salary, joinDate);
        }
    }

    public static void main(String[] args) {
        // 创建测试数据 (员工ID, 员工对象)
        Map<String, Employee> employeeMap = new HashMap<>();
        employeeMap.put("E1001", new Employee("张三", 15000, LocalDate.of(2020, 3, 15)));
        employeeMap.put("E1002", new Employee("李四", 18000, LocalDate.of(2019, 7, 1)));
        employeeMap.put("E1003", new Employee("王五", 15000, LocalDate.of(2021, 5, 20)));
        employeeMap.put("E1004", new Employee("赵六", 22000, LocalDate.of(2018, 12, 10)));
        employeeMap.put("E1005", new Employee("钱七", 18000, LocalDate.of(2020, 9, 5)));

        // 1. 将Map转换为可排序的Entry列表
        List<Map.Entry<String, Employee>> entries = new ArrayList<>(employeeMap.entrySet());

        // 2. 创建多级排序规则
        Comparator<Map.Entry<String, Employee>> salaryComparator = 
            (e1, e2) -> Double.compare(e2.getValue().salary, e1.getValue().salary);
        
        Comparator<Map.Entry<String, Employee>> dateComparator = 
            (e1, e2) -> e1.getValue().joinDate.compareTo(e2.getValue().joinDate);
        
        Comparator<Map.Entry<String, Employee>> nameComparator = 
            (e1, e2) -> e1.getValue().name.compareTo(e2.getValue().name);

        // 3. 组合排序规则 (薪资降序 -> 入职日期升序 -> 姓名升序)
        Comparator<Map.Entry<String, Employee>> combinedComparator = 
            salaryComparator
                .thenComparing(dateComparator)
                .thenComparing(nameComparator);

        // 4. 执行排序
        entries.sort(combinedComparator);

        // 5. 将排序结果存入LinkedHashMap (保持插入顺序)
        Map<String, Employee> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<String, Employee> entry : entries) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        // 打印排序结果
        System.out.println("员工ID | 员工详情");
        System.out.println("-------------------------------");
        sortedMap.forEach((id, emp) -> 
            System.out.println(id + " -> " + emp));
    }
}